//
//  StringWithHtmlUtil.m
//  JiaoX
//
//  Created by jiaoxiu－005 on 15/2/3.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//

#import "StringWithHtmlUtil.h"
#import "RegexKitLite.h"
@implementation StringWithHtmlUtil

NSString* regEx_script = @"<script[^>]*?>[\\s\\S]*?<\\/script>";// 定义script的正则表达式
NSString* regEx_style = @"<style[^>]*?>[\\s\\S]*?<\\/style>";// 定义style的正则表达式
NSString* regEx_html = @"<[^>]+>";// 定义HTML标签的正则表达式
NSString* regEx_space = @"\\s*|\t|\r|\n";//定义空格回车换行符

/**
 * 删除Html标签
 */
+(NSString*)delHTMLTag:(NSString*)htmlStr
{
    NSError* error = NULL;
    NSRegularExpression* p_script = [NSRegularExpression regularExpressionWithPattern:regEx_script options:0 error:&error];
    htmlStr = [p_script stringByReplacingMatchesInString:htmlStr options:0 range:NSMakeRange(0, htmlStr.length) withTemplate:@"$1$2"];
    
    NSRegularExpression* p_style = [NSRegularExpression regularExpressionWithPattern:regEx_style options:0 error:&error];
    htmlStr = [p_style stringByReplacingMatchesInString:htmlStr options:0 range:NSMakeRange(0, htmlStr.length) withTemplate:@"$1$2"];
    
    NSRegularExpression* p_html = [NSRegularExpression regularExpressionWithPattern:regEx_html options:0 error:&error];
    htmlStr = [p_html stringByReplacingMatchesInString:htmlStr options:0 range:NSMakeRange(0, htmlStr.length) withTemplate:@"$1$2"];
    
    NSRegularExpression* p_space = [NSRegularExpression regularExpressionWithPattern:regEx_space options:0 error:&error];
    htmlStr = [p_space stringByReplacingMatchesInString:htmlStr options:0 range:NSMakeRange(0, htmlStr.length) withTemplate:@"$1$2"];
    
    return htmlStr;
}

/**
 * 获取html中的文本
 */
+(NSString*)getTextFromHtml:(NSString*)htmlStr
{
    htmlStr = [StringWithHtmlUtil delHTMLTag:htmlStr];
    htmlStr = [htmlStr stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@""];
    
    //分享的字符串长度不要超过30
    if([htmlStr length]>30)
        return [htmlStr substringWithRange:NSMakeRange(0, 30)];
    else
        return htmlStr;
}

/**
 * 获取html中的第一张图片
 */
+(NSString*)getForumContextFirstImg:(NSString*)content{
    NSString* path = nil;
    NSString *regex = @"<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>";
    NSArray *array = [content componentsMatchedByRegex:regex];
    JXLog(@"%@",array[0]);
    if(array.count){
        NSString *result = [array[0] stringByReplacingOccurrencesOfString:@"'" withString:@"\""];
        NSArray* array2 = [result componentsSeparatedByString:@"\""];
        path = array2[1];
        JXLog(@"%@",array2[1]);
    }
    return path;
}
@end
